import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * </p>
 *
 * @author zhuolin
 * @since 2020/6/3
 */
public class ReadWriteDemo {

    private static Lock lock = new ReentrantLock();

    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    private static Lock readLock = reentrantReadWriteLock.readLock();

    private static Lock writeLock = reentrantReadWriteLock.writeLock();

    private int value;


    public Object handleRead(Lock lock) throws InterruptedException {
        try {
            while (true) {
                lock.lock();
                System.out.println("handleRead:" + value);
                Thread.sleep(1000);
                return value;
            }
        } finally {
            System.out.println("releaseRead");
            lock.unlock();
        }
    }

    public void handleWrite(Lock lock, Integer index) throws InterruptedException {
        try {
            lock.lock();
            System.out.println("handleWrite:" + index);
            Thread.sleep(1000);
            value = index;
        } finally {
            System.out.println("releaseWrite");
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final ReadWriteDemo demo = new ReadWriteDemo();
        Runnable readRunnable = () -> {
            try {
                demo.handleRead(readLock);
//                demo.handleRead(lock);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        };

        Runnable writeRunnable = () -> {
            try {
                demo.handleWrite(writeLock, new Random().nextInt());
//                demo.handleWrite(lock, new Random().nextInt());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        for (int i = 0; i < 18; i++) {
            new Thread(readRunnable).start();
        }
        for (int i = 18; i < 20; i++) {
            new Thread(writeRunnable).start();
        }
    }
}
